<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3个meta标签*必须*放在最前面，任何其他内容都*必须*跟随其后！ -->
    <title>Bootstrap 101 Template</title>

    <!-- Bootstrap -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim 和 Respond.js 是为了让 IE8 支持 HTML5 元素和媒体查询（media queries）功能 -->
    <!-- 警告：通过 file:// 协议（就是直接将 html 页面拖拽到浏览器中）访问页面时 Respond.js 不起作用 -->
    <!--[if lt IE 9]>
    <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
    <![endif]-->
</head>
<body>
<div class="container">
    <!--标题部分-->
    <div>
        <h1>系统公告客户端设计及实现(Bootstrap+jquery)</h1>
    </div>
    <!--内容部分-->
    <div>
        <div id="noticeListContainer">
            <from id="queryForm" style="display: inline">
                <input type="text" name="title" placeholder="请输入标题">
                <input type="button" value="查询" onclick="doQueryNotices()">
            </from>
            <button onclick="doDisplay()">添加</button>
            <table class="table">
                <thead>
                    <tr>
                        <th>序号</th>
                        <th>标题</th>
                        <th>类型</th>
                        <th>状态</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td colspan="6">数据正在加载中......</td>
                    </tr>
                </tbody>
            </table>
            <div class="pagination">
                <button class="pre">上一页</button>
                <button class="percent">1/1</button>
                <button class="next">下一页</button>
                <form id="pageForm" style="display: inline">
                    <input type="text" name="pageCurrent">
                    <input type="button" value="跳转" class="jump">
                </form>
            </div>
        </div>

        <div  id="noticeEditContainer" style="display: none">
            <h2>编辑区</h2>
            <form id="noticeEditForm">
                <input type="hidden" id="id">
                <div class="form-group">
                    <label for="typeId">类型:</label>
                    <select class="form-control" id="typeId">
                        <option value="1">通知</option>
                        <option value="2">公告</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="titleId">标题:</label>
                    <input type="text" class="form-control" id="titleId" placeholder="请输入标题">
                </div>
                <div class="form-group">
                    <label for="contentId">内容:</label>
                    <textarea class="form-control" rows="5" id="contentId" placeholder="请输入内容"></textarea>
                </div>
                <div class="form-group">
                    <label>状态:</label>
                    <label class="radio-inline">
                        <input type="radio" name="status" value="0" checked>正常
                    </label>
                    <label class="radio-inline">
                        <input type="radio" name="status" value="1">关闭
                    </label>
                </div>
                <button type="button" class="btn btn-default submit" onclick="doSaveOrUpdate()">提交</button>
                <button type="button" class="btn btn-default cancel" onclick="doBack()">取消</button>
            </form>
        </div>
    </div>
</div>

<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery，所以必须放在前边) -->
<script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
<script>
    $(function(){ // 页面加载完成执行
        doGetNotices();
        // 分页事件注册及处理
        $(".pagination").on("click",".pre,.next,.jump",doJumpToPage);
    });

    function doBack(){
        $("#noticeEditContainer").css("display","none");
        $("#noticeListContainer").css("display","block");
    }
    function doDisplay(){
        $("#noticeListContainer").css("display","none");
        $("#noticeEditContainer").css("display","block");
        doRestForm();
    }
    function doQueryNotices(){
        localStorage.setItem("pageCurrent",1);
        doGetNotices();
    }

    function doJumpToPage(){
        let cls=$(this).prop("class");
        let pageCurrent = parseInt(localStorage.getItem("pageCurrent"));
        let pageCount = parseInt(localStorage.getItem("pageCount"));
        if(cls=="pre"&&pageCurrent>1){
            pageCurrent--;
        }else if(cls=="next"&&pageCurrent<pageCount){
            pageCurrent++;
        }else if(cls=="jump"){
            let pageC=parseInt($("#pageForm input[name=pageCurrent]").val());
            if(pageC<1 || pageC>pageCount){
                alert("页码值不正确");
                $("#pageForm input[name=pageCurrent]").val("");
                return;
            }
            pageCurrent=pageC;
            $("#pageForm input[name=pageCurrent]").val("");
        }else {
            return;
        }
        // console.log(pageCurrent);
        localStorage.setItem("pageCurrent",pageCurrent);
        doGetNotices();
    }
    function doGetNotices() {
        let pageCurrent = localStorage.getItem("pageCurrent");
        if(pageCurrent==''||pageCurrent=='NaN') pageCurrent=1;
        let params={pageCurrent:pageCurrent};
        let title=$("#queryForm input[name=title]").val();
        params.title=title;
        let url="http://localhost/notice/";
        // 基于jQuery中的ajax函数向服务端发送请求
        $.ajax({
            method:"GET",
            data:params,
            url:url,
            success(result){
                //console.log(result);
                doHandleQueryResponseResult(result);
            }
        })
    }
    function doHandleQueryResponseResult(result){
        if(result.state==1){
            doHandleQueryOk(result);
        }
        else{
            doHandleQueryError();
        }
    }
    function doHandleQueryError(){
        let tBody=$("table>tbody");
        let len=$("table>thead>tr>th").length;
        let tr=`<tr><td colspan=${len}>未找到对应的记录</td></tr>`;
        tBody.html(tr);
        $(".percent").html("1/1");
    }
    function doHandleQueryOk(result){
        let records=result.data.list;
        doSetTableBodyRows(records);
        if (records.length>0)
            doSetPagination(result);
    }
    function doSetPagination(result){
        let pageCurrent = result.data.pageNum;
        let pageCount = result.data.pages;
        $(".percent").html(pageCurrent+"/"+pageCount);
        localStorage.setItem("pageCurrent",pageCurrent);
        localStorage.setItem("pageCount",pageCount);
    }
    function doSetTableBodyRows(records){
        let tBody=$("tbody");
        tBody.empty();
        // console.log("records",records);
        if(records.length==0){
            doHandleQueryError();
            return;
        }
        //js原生函数
        records.forEach((item,i)=>tBody.append(doCreateRow(item,i)))
        //jQuery中的函数
        //$.each(records,(i,item)=>tBody.append(doCreateRow(item,i)))
    }
    function doCreateRow(item,i){
        return `<tr>
                    <td>${i+1}</td>
                    <td>${item.title}</td>
                    <td>${item.type=='1'?"通知":"公告"}</td>
                    <td>${item.status=='0'?"正常":"关闭"}</td>
                    <td>${item.createdTime}</td>
                    <td>
                        <button class="btn btn-danger btn-xs" onclick="doDeleteById(${item.id})">delete</button>
                        <button class="btn btn-default btn-xs" onclick="doFindById(${item.id})">update</button>
                    </td>
                </tr>`;
    }
    function doFindById(id){
        let url=`http://localhost/notice/${id}`;
        // 发送异步请求
        $.ajax({
            url:url,
            success(result){
                if(result.state==1){
                    doInitEditForm(result);
                }else{
                    alert("可能记录已经被删除");
                }
            }
        });
    }
    function doInitEditForm(result){
        $("#id").val(result.data.id);
        $(`#noticeEditForm select>option[value=${result.data.type}]`).prop("selected",true);
        $("#titleId").val(result.data.title);
        $("#contentId").val(result.data.content);
        $(`#noticeEditForm input[value=${result.data.status}]:radio`).prop("checked",true);
    }
    function doSaveOrUpdate(){
        //1.获取请求参数
        let params={
            id:$("#id").val(),
            type:$("#typeId").val(),
            title:$("#titleId").val(),
            content:$("#contentId").val(),
            status:$("#noticeEditForm input:radio:checked").val()
        }
        //2.定义请求url
        let url="http://localhost/notice/";
        //3.发送异步请求
        $.ajax({
            method:params.id?"put":"post",
            url:url,
            data:JSON.stringify(params),//将js对象转换为json字符串
            contentType:"application/json",//向服务端传递的数据类型
            success(result){
                if(result.state==1){
                    alert(result.message);
                    doGetNotices();
                    doRestForm();
                    doBack();
                }else{
                    alert(result.message);
                }
            }
        });
    }
    function doRestForm(){//重置表单数据
        $("#id").val("");
        $(`#noticeEditForm select>option[value=1]`).prop("selected",true);
        $("#titleId").val("");
        $("#contentId").val("");
        $(`#noticeEditForm input[value=0]:radio`).prop("checked",true)
    }

    function doDeleteById(id){
        let url=`http://localhost/notice/${id}`;
        // 发送异步请求
        $.ajax({
            method:"delete",
            url:url,
            success(result){
                doHandleDeleteResponseResult(result);
            }
        });
    }
    function doHandleDeleteResponseResult(result){
        if(result.state==1){
            doHandelDeleteOk(result.message);
        }else{
            alert(result.message);
        }
    }
    function doHandelDeleteOk(msg){
        alert(msg);
        let rows=$("table>tbody>tr").length;
        let pageCurrent=parseInt(localStorage.getItem("pageCurrent"));
        let pageCount=parseInt(localStorage.getItem("pageCount"));
        if(pageCurrent>1&&pageCurrent==pageCount&&rows==1){
            pageCurrent--;
            localStorage.setItem("pageCurrent",pageCurrent);
        }
        doGetNotices();
    }
</script>

</body>
</html>